import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import dataTableCreate from '../addons/DataTable'
import dataImportCreate from '../addons/DataImport'
import * as menuService from '../../services/menus';
import * as compDiviService from '../../services/AccountDivi';
const daoName = "User";
const ButtonGroup = Button.Group;
const columns = [
  { title: '员工编号', dataIndex: 'No', key: 'No', width: 120, sorter: true, dispaly: true, filter: true },
  { title: '员工名称', width: 150, sorter: true, dataIndex: 'Name', key: 'Name', dispaly: true, filter: true },
  { title: '所属部门', width: 150, sorter: true, key: 'OrganizationID', caption: "Organization.Name", render: data => data.Organization.Name, dispaly: true, filter: true },
  { title: '零售管户人', width: 150, sorter: true, key: 'ISLSGHR', render: data => data.ISLSGHR === 1 ? '是' : '否', dispaly: true, filter: true },

];
const controls = [
  { name: 'No', required: true, type: 'alphanum', min: 6, max: 10, label: '员工编号', grid: 12 / 24 },
  { name: 'Name', required: true, type: 'text', label: '员工名称', min: 2, max: 30, grid: 12 / 24 },
  {
    name: "OrganizationID", label: "所属部门", type: "tree-select", grid: 12 / 24, filterAble: true, required: true,
    dataType: "number", fetch: { daoName: "Organization", optionTpl: 'Name', valueTpl: "ID" }
  },
  {
    name: "ISLSGHR", label: "零售管户人", required: true, data: [{ value: 1, label: '是' }, { value: 0, label: '否' }], grid: 12 / 24, type: "radio-group"
    , layout: { labelSpan: 7, wrapperSpan: 14 }
  },
]

const controls2 = [
  { name: 'No', required: true, type: 'alphanum', min: 6, max: 10, label: '员工编号', grid: 12 / 24 },
  { name: 'Name', required: true, type: 'text', label: '员工名称', min: 2, max: 30, grid: 12 / 24 },
  {
    name: "OrganizationID", label: "所属部门", type: "tree-select", grid: 12 / 24, filterAble: true, required: true,
    dataType: "number", fetch: { daoName: "Organization", optionTpl: 'Name', valueTpl: "ID" }
  },
  {
    name: "ISLSGHR", label: "零售管户人", required: true, data: [{ value: 1, label: '是' }, { value: 0, label: '否' }], grid: 12 / 24, type: "radio-group"
    , layout: { labelSpan: 7, wrapperSpan: 14 }
  },
]


const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
const DataImport = dataImportCreate(daoName);
class UsersGhr extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false
    };
  }
  componentDidMount() {
    const permID = this.props.permID
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: this.props.permID }
    });
    let { pOrgID, popedomTypes } = this.props
    const pTypes = popedomTypes[permID]
    let seeks = []

    if (pTypes.indexOf("4") == -1 && pTypes.indexOf("O") !== -1) {
      seeks = [{
        WhereItems: [{
          FieldName: "OrganizationID",
          Operator: "=",
          FieldValues: '' + pOrgID
        }, {
          FieldName: "Organization.ParentID",
          Operator: "in",
          FieldValues: '' + pOrgID
        }],
        RelationSign: "OR"
      }]
    }
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
    this.loadOptionData();
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  //新增和修改
  showModelHandler(isAdd) {
    let { record } = this.props
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  //删除数据
  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
  }
  //保存
  edidOkHandler() {
    let name = ''
    const form = this.refs.userForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const { keyName, record } = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? null : new Date(values[c.name])
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        if (record[keyName]) {
          this.state.dataChange = true;
          this.props.dispatch({
            type: t,
            payload: { daoName, values },
          })
        }
        name = values.Name;
        menuService.GetSysUserName({ name }
        ).then(function (data) {
          if (!record[keyName]) {
            if (data === "1") {
              Modal.confirm({
                title: '提示',
                content: `该员工名称在系统中已存在,确定要添加吗？`,
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                  this.state.dataChange = true;
                  this.props.dispatch({
                    type: t,
                    payload: { daoName, values },
                  })
                }
              })
            } else {
              this.state.dataChange = true;
              this.props.dispatch({
                type: t,
                payload: { daoName, values },
              })
            }
          }
        }.bind(this)).catch(function (ex) {
          console.log(ex)
        });
      }
    });
  };
  //关闭
  hideEditHandler() {
    const form = this.refs.userForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  //导入
  showImportHandler() {
    this.props.dispatch({
      type: `${daoName}_DataImport/setDisplay`,
      payload: { display: true },
    });
  }
  //初始化密码
  initPassword() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择初始化密码的用户！');
      return;
    }
    let userIDs = keys
    Modal.confirm({
      title: '提示',
      content: `你确认要将所选员工的密码进行初始化吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        menuService.initPasswordFetch({ userIDs }
        ).then(function (data) {
          if (data === 'ok') {
            message.success("密码初始化成功！初始化密码为(8个0)：00000000")
          }
        }.bind(this)).catch(function (ex) {
          console.log(ex)
        });
        this.props.dispatch({
          type: `${daoName}/setSelectedRowKeys`,
          payload: { selectedRowKeys: [] }
        });
      }
    });
  }
  SetUsingGhr() {
    let isOK = true;
    let status = ""
    const form = this.refs.selectY.getForm();
    form.validateFields((err, values) => {
      if (!err) {
        if (values.status === undefined || values.status === '') {
          message.error('请选择要设置的员工管户状态!');
          isOK = false;
        }
        status = values.status
      }
    })
    if (!isOK) {
      return;
    }
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择设置的员工列表！');
      return;
    }
    let userIDs = keys
    Modal.confirm({
      title: '提示',
      content: `你确认要将所选员工设置成【${status === "1" ? "管户人" :  "非管户人"}】吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        menuService.SetUsingGhr({ userIDs, status }
        ).then(function (data) {
          if (data === 'ok') {
            message.success('设置状态成功！');
          }
        }.bind(this)).catch(function (ex) {
          console.log(ex)
        });
        this.props.dispatch({
          type: `${daoName}/setSelectedRowKeys`,
          payload: { selectedRowKeys: [] }
        });
        this.props.dispatch({
          type: `${daoName}/reload`,
          payload: { daoName },
        });
      }
    });
  }
  render() {
    let { showEdit, record, pOrgID, permID, popedomTypes } = this.props
    const pTypes = popedomTypes[permID]
    let data = null
    if (pTypes.indexOf("4") == -1 && pTypes.indexOf("O") !== -1) {
      controls[2].fetch.where = "ParentOrganID=" + pOrgID + " or ID=" + pOrgID
    } else {
      controls[2].fetch.where = ""
    }
    let controlsFilter = [{
      name: "status", label: "管户人",
      data: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
      grid: 5 / 24, type: "radio-group", layout: { labelSpan: 14, wrapperSpan: 10 },
    },
    {
      name: 'BT', type: 'button-group',
      data: [
        { value: '1', label: '设置', onClick: this.SetUsingGhr.bind(this) },
      ], grid: 2 / 24
    }
    ];


    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            {/* {data} */}
            <EditFrom ref="selectY" daoName={daoName} controls={controlsFilter} clearItemMargin={true} />
          </div>
          <Modal title="用户编辑" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
            footer={[
              <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
              <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
            ]}
          >
            <EditFrom ref="userForm" daoName={daoName} controls={controls} record={record} />
          </Modal>
          <DataTable ref="userTable" daoName={daoName} columns={columns} controls={controls2} permID={permID} multiSelect={true} />
          <DataImport title="员工信息" importName="user" daoName="User" keys={["No"]} paramNames={["OrganizationID"]} importMode="InsertAndUpdate" controls={controls} />
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes } = state.menus;
  const { display } = state[`${daoName}_DataImport`];
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record,
    showImport: display
  }
}
UsersGhr = connect(mapStateToProps)(UsersGhr)
export default UsersGhr;

let render = (props) => React.createElement(UsersGhr, props);
let f = new Factory()
f.set("UsersGhr", render)
